<?php

namespace App\Http\Controllers;

use App\Models\UserDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Validator;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;


class UserDetailController extends Controller
{
    const updateArr=['realname','student_id','grade','majority','classes','identity_id','phone'];
    const picType=['jpg','jpeg','png','bmp'];

    //更新个人信息（注：不包括头像信息，权限信息，认证信息）
   public function updateDetail(Request $request)
   {
       //验证数据
       $validator=Validator::make($request->all(),[
           "user_id"=>"required",
       ]);
       if($validator->fails())
       {
           return self::result(false,"请确定用户id",null);
       }
       $data=$request->all();

       $user=UserDetail::where('user_id',$data['user_id'])->first();

       if(!isset($user->id)) $user=new UserDetail();

       foreach (self::updateArr as $item)
       {
           if(isset($data[$item]))
           {
               $user->setAttribute($item,$data[$item]);
           }
       }

       $bool=$user->save();
       if($bool) return self::result(true,"更新成功",null);
       else return self::result(false,"更新失败",null);
   }

   //更新用户头像
   public function updateImg(Request $request)
   {
       $validator=Validator::make($request->all(),[
           "user_id"=>"required",
       ]);
       if($validator->fails())
       {
           return self::result(false,"请确定用户id",null);
       }
       if(!$request->hasFile("picture"))
       {
           return self::result(false,"请上传图片",null);
       }

       $data=$request->all();

       //如果不存在该user_detail,则新创建一个user_detail实例
       $user=UserDetail::where('user_id',$data['user_id'])->first();
       if(!isset($user->id)) $user=new UserDetail();
       //验证图片后缀类型
       $type=strtolower($request->file("picture")->getClientOriginalExtension());
       //dump($type);
       $bool=false;
       foreach(self::picType as $item)
       {
           if($bool=($item==$type)) break;
       }
       if($bool==false)
       {
           return self::result(false,"图片格式错误",null);
       }
       //生成图片名字
       $picname=$data['user_id']."%".str_random(20).".".$type;
       //dump($picname);
       //储存图片
       $user->user_id=$data['user_id'];
       $user->image=$picname;
       Storage::disk("avatar")->put($picname,file_get_contents($request->file('picture')->getRealPath()));
       $user->save();
       //返回图像的名称
       return self::result(true,"更新头像成功",$picname);
   }

   //获取用户头像（以二进制文本返回）
   public function getUserImg(Request $request)
   {
       $validator=Validator::make($request->all(),[
           "picname"=>"required",
       ]);
       if($validator->fails())
       {
           return self::result(false,"请指定图像路径",null);
       }
       $data=$request->all();
       if(Storage::disk('avatar')->exists($data['picname']))
       {
           //返回二进制流
           $headers = array(
               'Content-Type: image/*',
           );
           //返回图像
           return  response()->download(storage_path('app/avatar/'.$data['picname']),$data['picname'],$headers,'inline');
       }
       return null;
   }

   public function getUserImgById(Request $request)
   {
       $validator=Validator::make($request->all(),[
           "user_id"=>"required",
       ]);
       if($validator->fails())
       {
           return self::result(false,"请指定用户ID",null);
       }
       $data=$request->all();
       $user=DB::table('user_detail')->select('image')->where('user_id',$data['user_id'])->first();
       //dump($user);
       if(!isset($user->image)) return null;
       $imgurl=$user->image;
       if(Storage::disk('avatar')->exists($imgurl))
       {
           //返回二进制流
           $headers = array(
               'Content-Type: image/*',
           );
           //返回图像
           return  response()->download(storage_path('app/avatar/'.$imgurl),$imgurl,$headers,'inline');
       }
       return null;
   }


   public function getUserDetail(Request $request)
   {
       $validator=Validator::make($request->all(),[
           "user_id"=>"required",
       ]);
       if($validator->fails())
       {
           return self::result(false,"请确定用户id",null);
       }
       $data=$request->all();
       $user=UserDetail::where('user_id',$data['user_id'])->first();
       if(isset($user->id))
       {
           return self::result(true,"获取用户信息成功",$user->toArray());
       }
       return self::result(false,"获取用户信息失败",$user->toArray());

   }

   public function confirmPhone()
   {
       //手机号码认证
   }

   public function confirmStudentId()
   {
       //正方认证
   }

   public function confirmEmail()
   {
       //邮箱认证
   }







    public static function result($success,$info,$res)
    {
        return ['success'=>$success,'info'=>$info,'result'=>$res];
    }
}
